package it.polimi.reTraveldream.eao;

import it.polimi.reTravelDream.dto.ExcursionDTO;
import it.polimi.reTravelDream.eao.ExcursionEAOLocal;
import it.polimi.reTraveldream.entities.Excursion;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ExcursionEAO
 */
@Stateless
public class ExcursionEAO implements ExcursionEAOLocal{

	@PersistenceContext
    private EntityManager em;
	
    public ExcursionEAO() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void addExcursion(ExcursionDTO currentExcursion) {
		Excursion newExcursion= new Excursion(currentExcursion);
		em.persist(newExcursion);
	}

	@Override
	public List<ExcursionDTO> getAllExcursion() {
		List<Excursion> resultEntities= em.createNamedQuery(Excursion.FIND_ALL, Excursion.class)
                .getResultList();
		 List<ExcursionDTO> resultDTO= new ArrayList<ExcursionDTO>();
		 for (Excursion h: resultEntities){
			 resultDTO.add(convertToDTO(h));
		 }
		 return resultDTO;
	}
	
	 private ExcursionDTO convertToDTO(Excursion excursionEntity) {
			ExcursionDTO excursionDTO = new ExcursionDTO();
			excursionDTO.setId(excursionEntity.getId());
			excursionDTO.setDescription(excursionEntity.getDescription());
			excursionDTO.setName(excursionEntity.getName());
			excursionDTO.setPrice(excursionEntity.getPrice());
			excursionDTO.setActive(excursionEntity.isActive());
			return excursionDTO;		
		}

	@Override
	public void delete(ExcursionDTO currentExcursion) {
		Excursion excursion=em.find(Excursion.class, currentExcursion.getId());
		em.remove(excursion);		
	}

	@Override
	public void edit(ExcursionDTO currentExcursion) {
		Excursion  excursion= new Excursion(currentExcursion);	
		em.merge(excursion);
		
	}
	
}
